package com.sxf.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.pm.PackageManager;
import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import jcifs.smb.SmbFileOutputStream;

public class MainActivity extends AppCompatActivity {
    private Button mainButton;
    private TextView messageText;
    private int clickCount = 0;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        messageText = findViewById(R.id.textView);
        mainButton = findViewById(R.id.button);
        mainButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickCount++;
                messageText.setText("Button clicked " + clickCount + " times!");
                checkStoragePermission();
            }
        });

    }

    // 检查并请求权限的方法
    private void checkStoragePermission() {
        // 检查是否已有权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，向用户解释为什么需要这个权限（可选）
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // 显示解释对话框
                new AlertDialog.Builder(this)
                        .setTitle("需要存储权限")
                        .setMessage("应用需要访问存储权限来读取文件")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 请求权限
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                    REQUEST_CODE_STORAGE_PERMISSION);
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            } else {
                // 直接请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_STORAGE_PERMISSION);
            }
        } else {
            // 已经有权限，执行文件操作
            readFile();
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，执行文件操作
                readFile();
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "存储权限被拒绝，无法读取文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 读取文件的方法
    private void readFile() {
        new Thread(() -> {
            long startTime = System.currentTimeMillis();
            long preTime = startTime;
            long currentTime;
            long totalBytes = 0;
            long preBytes = 0;
            double speed;
            double speed2;

            // 使用更大的缓冲区提高传输效率
            byte[] buffer = new byte[64 * 1024]; // 64KB缓冲区

            MediaHelper mh = new MediaHelper("smb://192.168.1.115/public/a.dat", "WORKGROUP", "work", "123456");
            File file = new File("/storage/emulated/0/DCIM/Camera/VID_20211003_180114.mp4");

            try (InputStream in = new FileInputStream(file)) {
                int bytesRead;

                while ((bytesRead = in.read(buffer)) > 0) {
                    mh.write(buffer, bytesRead);
                    totalBytes += bytesRead;

                    // 可选：添加进度反馈
                    currentTime = System.currentTimeMillis();
                    if (currentTime - preTime > 1000) { // 每秒更新一次
                        speed = ((totalBytes - preBytes) / (1024.0 * 1024.0)) / ((currentTime - preTime) / 1000.0);
                        speed2 = (totalBytes / (1024.0 * 1024.0)) / ((currentTime - startTime) / 1000.0);
                        preTime = currentTime;
                        preBytes = totalBytes;
                        updateSpeedUI(speed, speed2, totalBytes, file.length());
                    }
                }
                mh.close();

                currentTime = System.currentTimeMillis();
                double duration = (currentTime - startTime) / 1000.0;
                speed = ((totalBytes - preBytes) / (1024.0 * 1024.0)) / ((currentTime - preTime) / 1000.0);
                speed2 = (totalBytes / (1024.0 * 1024.0)) / duration;
                updateSpeedUI(speed, speed2, totalBytes, file.length());
                String msg = String.format("传输完成! 耗时: %.2f s, 数据量: %.2f MB, 平均速度: %.2f MB/s",
                        duration, totalBytes / (1024.0 * 1024.0), speed2);
                Log.d("TransferStats", msg);
                // 在主线程显示Toast
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
                });

            } catch (IOException e) {
                long errorTime = System.currentTimeMillis();
                Log.e("TransferStats", "传输失败! 耗时: " + (errorTime - startTime) + " ms", e);

                // 错误提示也要在主线程显示
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "传输失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    // 更新速度显示的UI方法
    private void updateSpeedUI(double speed, double speed2, long transferred, long total) {
        runOnUiThread(() -> {
            // 这里可以更新UI显示当前速度
            messageText.setText(String.format("即时：%.2f MB/s\n平均：%.2f MB/s\n已传：%d\n总共：%d\n完成：%.2f%%", speed, speed2, transferred, total, 100.0*transferred/total));
        });
    }
}